
var net = require('net')
    var chatServer = net.createServer();
    var clientList = [];
    chatServer.on('connection', function(client) {

   	 // 无差别的发生信息
     /* client.write('Hi!\n');
      client.write('Bye!\n');
      // client.end();

      clientList.push(client);
      client.on('data', function(data) {
        
        for(var i = 0 ; i < clientList.length; i++){
        	clientList[i].write(data);
        }
		})
		*/

	  //排除自己的发送信息
	  // client.name = client.remoteAddress+":"+client.remotePort;
	  // client.write('Hi' + client.name +'!\n');
	  // clientList.push(client);
	  // client.on('data',function(data){
	  		
	  // 		for(var i  = 0; i < clientList.length;i++){

	  // 			if(clientList[i] != this){
	  // 				clientList[i].write(this.name+":\n"+data+"\n");
	  // 			}
	  			
	  			
	  // 		}

	  // })

	  /*增加robust*/
	  client.name = client.remoteAddress+":"+client.remotePort;
	  client.write('Hi' + client.name +'!\n');
	  console.log(client.name +"joined");
	  clientList.push(client);
	  client.on('data',function(data){
	  		broadcast(data,client);
	  		
	  });


	  client.on('end',function(data){
	  		console.log(client.name+"is break out");
	  		clientList.splice(clientList.indexOf(client),1);
	  })

	  client.on('error',function(e){
	  		console.log(e);
	  })

	  function broadcast(message,client){
	  		var cleanup = [];
	  		for(var i  = 0; i < clientList.length;i++){
	  			if(clientList[i] != client){
	  				if(clientList[i].writable){
	  					clientList[i].write(client.name+":\n"+message+"\n");
	  				}else{
	  					 cleanup.push(clientList[i]);
            			 clientList[i].destroy();
	  				}
	  				
	  			}
	  		}
	  		for(var i=0;i<cleanup.length;i+=1) {
        		clientList.splice(clientList.indexOf(cleanup[i]), 1);
			}
	  }


    })

    chatServer.listen(9000);
    console.log('server running at localhost:9000');